
package com.smc.common.utils;

import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * 关于异常的工具类.
 * 
 * @author zouqinghua
 * @date 2019年3月30日  下午11:43:39
 *
 */
public class Exceptions {

  /** 将CheckedException转换为UncheckedException. */
  public static RuntimeException unchecked(Exception e) {
    if (e instanceof RuntimeException) {
      return (RuntimeException) e;
    } else {
      return new RuntimeException(e);
    }
  }

  /** 将ErrorStack转化为String. */
  public static String getStackTraceAsString(Throwable e) {
    if (e == null) {
      return "";
    }
    StringWriter stringWriter = new StringWriter();
    e.printStackTrace(new PrintWriter(stringWriter));
    return stringWriter.toString();
  }

  /** 判断异常是否由某些底层的异常引起. */
  @SafeVarargs
  public static boolean isCausedBy(
      Exception ex, Class<? extends Exception>... causeExceptionClasses) {
    Throwable cause = ex.getCause();
    while (cause != null) {
      for (Class<? extends Exception> causeClass : causeExceptionClasses) {
        if (causeClass.isInstance(cause)) {
          return true;
        }
      }
      cause = cause.getCause();
    }
    return false;
  }

  /**
   * 在request中获取异常类
   *
   * @param request
   * @return
   */
  public static Throwable getThrowable(HttpServletRequest request) {
    Throwable ex = null;
    if (request.getAttribute("exception") != null) {
      ex = (Throwable) request.getAttribute("exception");
    } else if (request.getAttribute("javax.servlet.error.exception") != null) {
      ex = (Throwable) request.getAttribute("javax.servlet.error.exception");
    }
    return ex;
  }

  /**
   * 递归调用获取Root异常信息
   *
   * @param e
   * @return
   */
  public static Exception getRootException(Throwable e) {
    Exception ex = null;
    if (e != null) {
      try {
        Throwable t = e.getCause();
        if (t != null) {
          ex = getRootException(t);
        } else {
          ex = (Exception) e;
        }
      } catch (Exception e2) {
        e2.printStackTrace();
      }
    }

    return ex;
  }
  
  /**
   * 获取异常消息内容
   * @param ex
   * @return
   */
  public static String getExceptionMessage(Exception ex){
		String message = "";
		if(ex!=null){
			if(StringUtils.isBlank(message)){
				message = ex.getMessage();
			}
			if(StringUtils.isBlank(message)){
				Exception rootExcpetion = Exceptions.getRootException(ex);
				if(rootExcpetion!=null){
					message = rootExcpetion.getMessage();
				}
			}
		}
		return message;
	}
  
	public static String getExceptionMessage(Exception ex,Integer maxLen,String splitStr) {
		StringBuffer errorStackTraceMessage = new StringBuffer();
		StackTraceElement[] st = ex.getStackTrace();
		if (st != null && st.length > 0) {
			Integer len = maxLen; // 最大输出异常行数
			splitStr = splitStr==null?"</br>\n\t":splitStr;
			for (StackTraceElement e : st) {
				errorStackTraceMessage.append(e).append("</br>\n\t");
				if(len!=null){
					len--;
					if (len <= 0) {
						break;
					}
				}
			}
		}
		return errorStackTraceMessage.toString();
	}
}
